import http from '@/utils/http'
import { setTokenInfo } from '@/utils/storage'
import { AppDispatch } from '..'
import { Profile } from '../reducer/user'

/**
 * 发送短信验证码 '字符串：手机号'
 */
export const sendCodes = (mobile: string) => {
  return async () => {
    await http.get(`/v1_0/sms/codes/${mobile}`)
  }
}

/**
 * 用户认证（登录注册） {对象}
 * @mobile：手机号
 * @code：验证码
 */
export const Authorizations = ({ mobile, code }: { mobile: string; code: string }) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post(`/v1_0/authorizations`, { mobile, code })
    // 存到仓库
    dispatch({ type: 'user/token', payload: res.data })
    // 存到本地
    setTokenInfo(res.data)
  }
}

/**
 * 获取用户自己信息
 */
export const getUserInfo = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/user`)
    dispatch({ type: 'user/setInfo', payload: res.data })
  }
}

/**
 * 获取用户个人资料
 */
export const getUserProfile = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/user/profile`)
    // 后台的数据有一个没有的时候是null，我们需要处理一下
    if (!res.data.intro) res.data.intro = ''
    dispatch({ type: 'user/setProfile', payload: res.data })
  }
}

/**
 * 设置用户头像 FormData
 * @photo：e.target.files
 */
export const setUserPhoto = (fd: FormData) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.patch(`/v1_0/user/photo`, fd)
    dispatch({ type: 'user/setProfileOne', payload: res.data })
  }
}


/**
 * 设置用户其他资料 {对象}
 * @name:昵称 ; 
 * @gender:性别0-男1-女 ; 
 * @birthday:生日格式'2018-12-20' ; 
 * @real_name:真实姓名 ; 
 * @intro:个人介绍
 */
export const setUserInfo = (data: Partial<Profile>) => {
  return async (dispatch: AppDispatch) => {
    await http.patch(`/v1_0/user/profile`, data)
    dispatch({ type: 'user/setProfileOne', payload: data })
  }
}